import waves from "@/directive/waves";
import Pagination from "@/components/Pagination";
import { mapGetters } from 'vuex';
import PanThumb from "@/components/PanThumb";
import ImageCropper from "@/components/ImageCropper";
import {
  getDataList,
  save,
  deleteSelectedData,
  getSystemStructureTree,
  getRoleList,
  getAreaListDropdown
} from '../personnel-manage.service';
import { alertWithCallback, alertMessage } from '../../../utils/utils';
import { isValidateNull } from "../../../utils/utils";
import { validIdNo, validPhone } from "@/utils/validate";

export default {
  name: 'user-manage',
  components: { Pagination, PanThumb, ImageCropper },
  directives: { waves },
  data() {
    return {
      totalNum: 0, // 数据总数
      pageNum: 1, // 页数
      recordNum: 20, // 分页组件默认的页数, 分页里的select默认10, 20, 50
      queryString: "", // 搜索字段
      data: [], // 列表数据
      loading: true, // table loading
      detailDialogVisible: false, // 数据详情模态窗
      editDialogVisible: false, // 编辑详情模态窗
      selectedDataDetail: {}, // 选中数据详情
      editForm: {
        headImgUrl: ''
      }, // 编辑用户表单
      editRules: {
        trueName: [{ required: true, trigger: "change", validator: isValidateNull }],
        // selectedAreaId: [{ required: true, trigger: "change", validator: isValidateNull }],
        structName: [{ required: true, trigger: "change", validator: isValidateNull }],
        card: [{ trigger: "change", validator: validIdNo }],
        mobileNumber: [{ trigger: "change", validator: validPhone, message: '联系方式格式有误' }],
        enumSex: [{ required: true, trigger: "change", validator: isValidateNull }]
      }, // 编辑表单验证规则
      dialogTitle: '', // 编辑弹窗标题
      departmentDialogVisible: false, // 部门模态窗
      departmentList: [], // 部门树
      // 部门树变量
      defaultProps: {
        children: "children",
        label: "text"
      },
      roleList: [], // 角色列表
      areaList: [], // 区域列表
      file_url: process.env.VUE_APP_FILE_URL, // 头像url
      checkedRows: [] // table checkbox选中数据
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getDataList();
  },
  methods: {
    // 获取列表
    getDataList() {
      this.loading = true;
      getDataList(this.queryString, this.pageNum, this.recordNum).then(res => {
        this.totalNum = res.dataCount;
        this.data = res.data;
        this.loading = false;
      });
    },

    // 根据关键字进行搜索
    search() {
      this.pageNum = 1;
      this.getDataList();
    },

    // 重置搜索
    reset() {
      this.pageNum = 1;
      this.queryString = '';
      this.getDataList();
    },

    // 打开新建、编辑窗体
    openEditDialog(type, selectedData) {
      this.getRoleList();
      // this.getAreaList();
      this.getDepartmentTreeData();
      if (type === 'create') {
        this.dialogTitle = '新建';
        this.$nextTick(() => {
          // 重置必填项
          this.editForm = {
            headImgUrl: '',
            enumSex: '0',
            isEnable: true,
            password: '',
            selectedRoles: [],
            selectedAreaId: '',
            userName: '',
            structName: ''
          };
          this.$refs.dataForm.resetFields();
        });
      } else {
        this.dialogTitle = '编辑';
        this.$nextTick(() => {
          selectedData.selectedRoles = [];
          selectedData.dataChecks.forEach(item => {
            if (item.objectId && item.objectId != '') {
              selectedData.selectedRoles.push(item.objectId);
            }
          });
          selectedData.selectedAreaId = selectedData.regList.join('');
          this.editForm = Object.assign({}, selectedData);
          this.$refs.dataForm.resetFields();
        });
      }
      this.editDialogVisible = true;
    },

    // 创建或者编辑信息
    save() {
      // 表单验证
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.editForm.userName = this.editForm.isEnable ? this.editForm.userName : '';
          if (this.editForm.selectedAreaId && this.editForm.selectedAreaId != '') {
            this.editForm.regList = [this.editForm.selectedAreaId];
          }
          this.editForm.dataChecks = [];
          this.editForm.selectedRoles.forEach(item => {
            this.editForm.dataChecks.push({
              objectId: item,
              checkFlag: true
            });
          });
          save(this.editForm).then((res) => {
            this.editDialogVisible = false;
            alertMessage(res.message);
            this.reset();
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }
      });
    },

    // 删除选中数据
    deleteSelectedData(id) {
      if (id) {
        alertWithCallback('此操作将永久删除该数据, 是否继续?', '提示').then(() => {
          deleteSelectedData([id]).then((res) => {
            alertMessage(res.message);
            this.reset();
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
      } else {
        if (this.checkedRows.length == 0) {
          alertMessage('请选择记录', 'warning');
        } else {
          alertWithCallback('此操作将永久删除该数据, 是否继续?', '提示').then(() => {
            const ids = [];
            this.checkedRows.forEach(item => {
              ids.push(item.objectId)
            });
            deleteSelectedData(ids).then((res) => {
              alertMessage(res.message);
              this.reset();
            }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }
      }
    },

    // 设置单选
    setCheckNode(data, checked) {
      if (checked === true) {
        this.$refs.tree.setCheckedNodes([]);
        this.$refs.tree.setCheckedNodes([data]);
      }
    },

    // 获取部门树
    getDepartmentTreeData() {
      this.departmentList = [];
      getSystemStructureTree().then(data => {
        this.departmentList = data.data;
      }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
    },

    // 获取所选部门
    getDepartmentCheckedNodes() {
      const department = this.$refs.tree.getCheckedNodes(); // 获取所选节点信息
      if (department.length > 0) {
        this.editForm.structName = department[0].text;
        this.editForm.structId = department[0].id;
        this.departmentDialogVisible = false; // 关闭弹窗
      } else {
        alertMessage('请选择部门');
      }
    },

    // 打开选择部门窗体
    openDepartmentDialog() {
      this.departmentDialogVisible = true;
      if (this.editForm.structId && this.editForm.structId !== '') {
        setTimeout(() => {
          this.$refs.tree.setCheckedKeys([this.editForm.structId]);
        }, 100);
      }
    },

    // 上传头像
    handleAvatarSuccess(res, file) {
      this.editForm.headImgUrl = res.data;
    },

    // 删除头像
    handleAvatarRemove() {
      this.editForm.headImgUrl = '';
    },

    // 处理checkbox选中行数据
    handleSelectionChange(val) {
      this.checkedRows = val;
    },

    // 获取角色列表
    getRoleList() {
      getRoleList('', 1, 1000).then(res => {
        this.roleList = res.data;
      });
    },

    // 获取区域列表
    getAreaList() {
      const params = {
        pageNum: 0,
        recordNum: 0
      };
      this.areaList = [];
      getAreaListDropdown(params).then(res => {
        this.areaList = res.data.filter(item => {
          return item.isEnable == '1'
        });
      });
    },

    // 重置密码
    resetPwd() {
      this.editForm.password = '123456';
      alertMessage('重置密码成功, 请提交修改信息');
    }
  }
}
